package ae.pcfc.cldos.online.web.controller.generic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContextUtils;

import ae.pcfc.cldos.online.common.delegate.AdminTaskDelegate;
import ae.pcfc.cldos.online.common.delegate.CityDelegate;
import ae.pcfc.cldos.online.common.delegate.CompanyEmployeeDelegate;
import ae.pcfc.cldos.online.common.delegate.CompanyInformationDelegate;
import ae.pcfc.cldos.online.common.delegate.EmirateCityDelegate;
import ae.pcfc.cldos.online.common.delegate.GeneralAdminDelegate;
import ae.pcfc.cldos.online.common.delegate.SystemValuesDelegate;
import ae.pcfc.cldos.online.common.exception.LocatorException;
import ae.pcfc.cldos.online.common.exception.NoSuchCompanyException;
import ae.pcfc.cldos.online.common.vo.CityLabelVO;
import ae.pcfc.cldos.online.common.vo.FileVO;
import ae.pcfc.cldos.online.common.vo.LabelVO;
import ae.pcfc.cldos.online.common.vo.notifications.NotificationRequestParamsVO;
import ae.pcfc.cldos.online.common.vo.notifications.NotificationRequestVO;
import ae.pcfc.cldos.online.common.vo.notifications.NotificationVO;
import ae.pcfc.cldos.online.common.vo.notifications.NotificationsVO;
import ae.pcfc.cldos.online.common.vo.selectors.CityVO;
import ae.pcfc.cldos.online.common.vo.selectors.EmirateCityVO;
import ae.pcfc.cldos.online.common.vo.tasks.AdminTaskVO;
import ae.pcfc.cldos.online.common.vo.tasks.TaskRequestParamsVO;
import ae.pcfc.cldos.online.common.vo.tasks.TaskRequestVO;
import ae.pcfc.cldos.online.common.vo.tasks.TasksVO;
import ae.pcfc.cldos.online.net.service.vo.EmployeeDetailsFromGSVO;
import ae.pcfc.cldos.online.net.service.vo.ListOfEmployeeDetailsFromGSVO;
import ae.pcfc.cldos.online.web.ViewPath;
import ae.pcfc.cldos.online.web.controller.base.BaseController;
import ae.pcfc.cldos.online.web.model.AdminTaskGridSearchBean;
import ae.pcfc.cldos.online.web.model.EmployeeDataJSONModel;
import ae.pcfc.cldos.online.web.model.JQGridJSONModel;
import ae.pcfc.cldos.online.web.model.UserNotificationGridSearchBean;
import ae.pcfc.cldos.online.web.util.StringUtils;

@Controller
public class GenericAjaxController extends BaseController {
	
	@Autowired
	@Qualifier("cityDelegate")
	private CityDelegate cityDelegate;
	
	@Autowired
	@Qualifier("emirateCityDelegate")
	private EmirateCityDelegate emirateCityDelegate;
	
	@Autowired
	@Qualifier("adminTaskDelegate")
	private AdminTaskDelegate adminTaskDelegate;
	
	@Autowired
	@Qualifier("companyEmployeeDelegate")
	private CompanyEmployeeDelegate companyEmployeeDelegate;
	
	@Autowired
	@Qualifier("generalAdminDelegate")
	private GeneralAdminDelegate generalAdminDelegate;
	
	@Autowired
	@Qualifier("companyInformationDelegate")
	private CompanyInformationDelegate companyInformationDelegate;
	
	@Autowired
	@Qualifier("systemValuesDelegate")
	protected SystemValuesDelegate systemValuesDelegate;	
	

	@RequestMapping(value = "/city", method = RequestMethod.GET)
	@ResponseBody
	public List<LabelVO> getCitiesByCountryCode(HttpServletRequest request,
			@RequestParam(value = "contryCode", required = true) String countryCode, Locale locale) {
		
		List<LabelVO> labelList = new ArrayList<LabelVO>();
		CityLabelVO labelVO = new CityLabelVO();
		labelList.add(labelVO);
		
		List<CityVO> cities = cityDelegate.getCitiesByCountryCode(countryCode);
		
		for (CityVO cityVO : cities) {
			labelVO = cityDelegate.getMapper().map(cityVO, CityLabelVO.class);
			labelList.add(labelVO);
		}
		
		return labelList;
	}
	
	
	@RequestMapping(value = "/emiratecity", method = RequestMethod.GET)
	@ResponseBody
	public List<LabelVO> getEmirateCitiesByEmirateCode(HttpServletRequest request,
			@RequestParam(value = "emirateCode", required = true) String emirateCode, Locale locale) {
		
		List<LabelVO> labelList = new ArrayList<LabelVO>();
		LabelVO labelVO = new LabelVO();
		labelList.add(labelVO);
		
		List<EmirateCityVO> cities = emirateCityDelegate.getEmirateCitiesByEmirateCode(emirateCode);
		
		for (EmirateCityVO cityVO : cities) {
			labelVO = cityDelegate.getMapper().map(cityVO, LabelVO.class);
			labelList.add(labelVO);
		}
		
		return labelList;
	}
	
	
	
	@RequestMapping(value = "/displayUserTasks")
	public @ResponseBody
	JQGridJSONModel displayUserTasks(HttpServletRequest request, Locale locale,
			@ModelAttribute AdminTaskGridSearchBean adminTaskGridSearchBean,
			@RequestParam(value = "page", required = true) String page,
			@RequestParam(value = "rows", required = true) String rows,
			@RequestParam(value = "sidx", required = true) String sidx,
			@RequestParam(value = "sord", required = true, defaultValue = "asc") String sord,
			@RequestParam(value = "_search", required = false) String isSearch,
			@RequestParam(value = "searchField", required = false) String searchField,
			@RequestParam(value = "searchOper", required = false) String searchOper,
			@RequestParam(value = "searchString", required = false) String searchString,
			@RequestParam(value = "min", required = false, defaultValue="false") boolean isMin) {

		JQGridJSONModel result = new JQGridJSONModel();

		Integer pageIndx = 1;
		Integer count = new Integer(20); //this.userDelegate.getUserList().size();
		Integer limit = 40;
		try {
			pageIndx = Integer.parseInt(page);
		} catch (Exception nullexp) {
			pageIndx = 1;
		}
		try {
			limit = Integer.parseInt(rows);
		} catch (Exception nullexp) {
			pageIndx = 10;
		}
		
		TaskRequestVO taskRequestVO = new TaskRequestVO();
		
		taskRequestVO.setUserVO(getUserVO());
		
		TaskRequestParamsVO taskRequestParamsVO = new TaskRequestParamsVO();
		mapper.map(adminTaskGridSearchBean, taskRequestParamsVO);
		taskRequestParamsVO.setCuurentPage(pageIndx);
		taskRequestParamsVO.setRowsPerPage(limit);
		if(!sord.equals("asc")){
			taskRequestParamsVO.setSortAsc(false);
		}
		
		taskRequestVO.setTaskRequestParamsVO(taskRequestParamsVO);
		
		TasksVO tasksVO = adminTaskDelegate.getAdminTaskList(taskRequestVO);
		
		List<AdminTaskVO> adminTaskVOList = tasksVO.getAdminTaskVOs();

		Integer totalpages = 0;
		
		count = tasksVO.getTotal();
		
		if (count > 0)
			totalpages = (int) Math.ceil(((float) count) / (float) limit);
		else
			totalpages = 0;

		if (pageIndx > totalpages)
			pageIndx = totalpages;

		
		result.setPage(pageIndx.toString());
		result.setRecords(count + "");
		result.setTotal(totalpages + "");
		
		int i=0;
		for(AdminTaskVO adminTaskVO : adminTaskVOList){
			List<String> cells = new ArrayList<String>();
			
			//for the max one
			if(!isMin){
				cells.add(adminTaskVO.getAppId().toString());
				//cells.add(adminTaskVO.getTaskNameEn());
				//abed
				cells.add(messageSource.getMessage("CLDOS_TASK_MASTER_"+adminTaskVO.getTaskCode(), new Object[]{}, locale));
				//cells.add(adminTaskVO.getServiceNameEn()); 
				//abed
				cells.add(messageSource.getMessage("CLDOS_SERVICE_MASTER_"+adminTaskVO.getServiceCode(), new Object[]{}, locale));
				cells.add(adminTaskVO.getReferenceNo());
				cells.add(adminTaskVO.getDate().toString());
				//cells.add(adminTaskVO.getStatus());
				//abed
				cells.add(messageSource.getMessage("CLDOS_APPLICATION_STATUS_"+adminTaskVO.getStatusCode(), new Object[]{}, locale));
				cells.add("<a href='"+ViewPath.__TASK+"?appId="+(encryptionDelegate.encryptAndEncode(adminTaskVO.getAppId().toString()))
						+"'><img src=\"resources/images/common/view_icon.jpg\" alt=\"open\"></a>");
			//for the home page dash-board minimal
			} else {
				//cells.add(adminTaskVO.getTaskNameEn());
				//cells.add(adminTaskVO.getServiceNameEn());
				//abed
				cells.add(messageSource.getMessage("CLDOS_TASK_MASTER_"+adminTaskVO.getTaskCode(), new Object[]{}, locale));
				cells.add(messageSource.getMessage("CLDOS_SERVICE_MASTER_"+adminTaskVO.getServiceCode(), new Object[]{}, locale));
				cells.add(adminTaskVO.getReferenceNo());
			}
			result.addRows((i++)+"", cells);
		}
		
		return result;
	}
	
	@RequestMapping(value = "/displayUserNotification")
	public @ResponseBody
	JQGridJSONModel displayUserNotifications(HttpServletRequest request, Locale locale,
			@ModelAttribute UserNotificationGridSearchBean userNotificationGridSearchBean,
			@RequestParam(value = "page", required = true) String page,
			@RequestParam(value = "rows", required = true) String rows,
			@RequestParam(value = "sidx", required = true) String sidx,
			@RequestParam(value = "displayReaded", required = false, defaultValue="false") boolean displayReaded,
			@RequestParam(value = "sord", required = true, defaultValue = "asc") String sord ,
			@RequestParam(value = "min", required = false, defaultValue="false") boolean isMin){

		JQGridJSONModel result = new JQGridJSONModel();

		Integer pageIndx = 1;
		
		
		Integer limit = 4;
		try {
			pageIndx = Integer.parseInt(page);
		} catch (Exception nullexp) {
			pageIndx = 1;
		}
		try {
			limit = Integer.parseInt(rows);
		} catch (Exception nullexp) {
			pageIndx = 10;
		}
		
		NotificationRequestVO notificationRequestVO = new NotificationRequestVO();
		
		notificationRequestVO.setUserVO(getUserVO());
		
		NotificationRequestParamsVO notificationRequestParamsVO = new NotificationRequestParamsVO();
		mapper.map(userNotificationGridSearchBean, notificationRequestParamsVO);
		notificationRequestParamsVO.setCuurentPage(pageIndx);
		notificationRequestParamsVO.setRowsPerPage(limit);
		notificationRequestParamsVO.setDisplayReaded(displayReaded);
		if(!sord.equals("asc")){
			notificationRequestParamsVO.setSortAsc(false);
		}
		
		notificationRequestVO.setNotificationRequestParamsVO(notificationRequestParamsVO);
		
		NotificationsVO notificationsVO = adminTaskDelegate.getUserNotifications(notificationRequestVO);
		List<NotificationVO> notificationVOs = notificationsVO.getNotificationVOs(); 

		int i=0;
		for(NotificationVO notificationVO : notificationVOs){
			List<String> cells = new ArrayList<String>();
			if(!isMin){
				String notificationId = notificationVO.getNotificationId();
				if(notificationVO.isUnreaded()){
					notificationId+=" <span style=\"color:red;\">*</span>";
				}
				cells.add(notificationId);
				//cells.add(notificationVO.getServiceName());
				//abed
				cells.add(messageSource.getMessage("CLDOS_SERVICE_MASTER_"+notificationVO.getServiceCode(), new Object[]{}, locale));
				cells.add(notificationVO.getClientRefNo());
				if(new Locale("ar","","").getLanguage().equalsIgnoreCase(locale.getLanguage())){
					cells.add(notificationVO.getSubjectAr());
				}else{
					cells.add(notificationVO.getSubject());
				}
				cells.add(notificationVO.getDate().toString());
				StringBuilder attachments = new StringBuilder();
				if(notificationVO.getFileVOs()!=null){
					for(FileVO fileVO : notificationVO.getFileVOs()){
						attachments.append("<a style='color:red' href='");
						attachments.append(ViewPath.__GS_FILE);
						attachments.append("/");
						if(fileVO.getId()==null)fileVO.setId(-1l);//::TODO FIXME .NET DONT SET ONLINE FILE ID FUCKFUCKFUCKFUCK
						attachments.append(encryptionDelegate.encryptAndEncode(fileVO.getId().toString()));
						attachments.append("'>");
						attachments.append(fileVO.getFileName());
						attachments.append("</a>&nbsp;");
					}
				}
				
				cells.add(attachments.toString());
				cells.add("<a href='admin/general/inbox/notifications/details/view.htm?msgId="
				+(encryptionDelegate.encryptAndEncode(notificationVO.getNotificationId()))+"'><img src=\"resources/images/common/view_icon.jpg\" alt=\"open\"></a>");

			} else {
				if(new Locale("ar","","").getLanguage().equalsIgnoreCase(locale.getLanguage())){
					cells.add(notificationVO.getSubjectAr());
				}else{
					cells.add(notificationVO.getSubject());
				}
				cells.add(notificationVO.getClientRefNo());
				cells.add(notificationVO.getDate().toString());
			}
			//cells.add("URL ATATATTA");
			result.addRows((i++)+"", cells);
		}
		
		Integer totalpages = 0;
		Integer count = notificationsVO.getTotal();
		if (count > 0)
			totalpages = (int) Math.ceil(((float) count) / (float) limit);
		else
			totalpages = 0;

		if (pageIndx > totalpages)
			pageIndx = totalpages;
		
		result.setPage(pageIndx.toString());
		result.setRecords(count + "");
		result.setTotal(totalpages + "");
		
		return result;
	}
	
	@RequestMapping(value = "/showEmployes")
	public @ResponseBody
	JQGridJSONModel showEmployes(HttpServletRequest request, 
			@RequestParam(value = "page", required = true) String page,
			@RequestParam(value = "rows", required = true) String rows,
			@RequestParam(value = "sidx", required = true) String sidx,
			@RequestParam(value = "sord", required = true, defaultValue = "asc") String sord ,
			@RequestParam(value = "min", required = false, defaultValue="false") boolean isMin,
			@RequestParam(value = "isVisitorsRequest", required = false, defaultValue="false") boolean isVisitorsRequest){

		JQGridJSONModel result = new JQGridJSONModel();

		Integer pageIndx = 1;
		
		
		Integer limit = 4;
		try {
			pageIndx = Integer.parseInt(page);
		} catch (Exception nullexp) {
			pageIndx = 1;
		}
		try {
			limit = Integer.parseInt(rows);
		} catch (Exception nullexp) {
			pageIndx = 10;
		}
		
		ListOfEmployeeDetailsFromGSVO listOfEmployeeDetailsFromGSVO = null;
		if(isVisitorsRequest){
			listOfEmployeeDetailsFromGSVO = companyEmployeeDelegate.getVisitorsDetailsList(getUserVO(), pageIndx, limit); 
		} else {
			listOfEmployeeDetailsFromGSVO = 
					companyEmployeeDelegate.getEmployeDetailsList(getUserVO(), pageIndx, limit);
		}
		
		List<EmployeeDetailsFromGSVO> detailsFromGSVOs = listOfEmployeeDetailsFromGSVO.getEmployeeDetailsFromGSVOList();
		int i=0;
		for(EmployeeDetailsFromGSVO employeeDetailsFromGSVO : detailsFromGSVOs){
			List<String> cells = new ArrayList<String>();
			cells.add(employeeDetailsFromGSVO.getEmployeeId());
			cells.add(employeeDetailsFromGSVO.getEmpNameEn());
			cells.add(employeeDetailsFromGSVO.getEmpNameAr());
			cells.add(employeeDetailsFromGSVO.getEmployeeStatus());
			cells.add(employeeDetailsFromGSVO.getPermitNo());
			cells.add(StringUtils.getDateString(employeeDetailsFromGSVO.getIssueDate()));
			cells.add(StringUtils.getDateString(employeeDetailsFromGSVO.getExpDate()));
			cells.add(employeeDetailsFromGSVO.getPostNo());
			cells.add(employeeDetailsFromGSVO.getNationality());
			cells.add(employeeDetailsFromGSVO.getCecNo());
			result.addRows((i++)+"", cells);
		}
		
		Integer totalpages = 0;
		Integer count = listOfEmployeeDetailsFromGSVO.getTotal();
		if (count > 0)
			totalpages = (int) Math.ceil(((float) count) / (float) limit);
		else
			totalpages = 0;

		if (pageIndx > totalpages)
			pageIndx = totalpages;
		
		result.setPage(pageIndx.toString());
		result.setRecords(count + "");
		result.setTotal(totalpages + "");
		
		return result;
	}
	
	@RequestMapping(value = "/getEmployeeData")
	public @ResponseBody EmployeeDataJSONModel getEmployeeData(@RequestParam String empId,
			@RequestParam(required=false, defaultValue="false") boolean isVisitor){
		
		EmployeeDataJSONModel employeeDataJSONModel = new EmployeeDataJSONModel();
		EmployeeDetailsFromGSVO employeeDetailsFromGSVO = null; 
		if(isVisitor){
			employeeDetailsFromGSVO = companyEmployeeDelegate.getVisitorDetailsById(empId, getUserVO());
		} else {
			employeeDetailsFromGSVO = companyEmployeeDelegate.getEmployeeDetailsById(getUserVO(), empId);
		}
		mapper.map(employeeDetailsFromGSVO, employeeDataJSONModel);
		employeeDataJSONModel.setExpDate(StringUtils.getDateString(employeeDetailsFromGSVO.getExpDate()));
		employeeDataJSONModel.setIssueDate(StringUtils.getDateString(employeeDetailsFromGSVO.getIssueDate()));
		return employeeDataJSONModel;
	}
	
	@RequestMapping(value = "/markNotificationAsReaded/{mesId}", method=RequestMethod.POST)
	public @ResponseBody String markNotificationAsReaded(@PathVariable String mesId){
		adminTaskDelegate.markNotificationAsReaded(mesId, getUserVO());
		return "Ok";
	}
	
	
	@RequestMapping(value = "/getInitiatedByFromAppMetaData")
	public @ResponseBody String getInitiatedByFromAppMetaData(@RequestParam String appId){
		
		String initiatedBy = "";
		try {
			initiatedBy =  generalAdminDelegate.getInitiatedByFromAppMetaDataById(appId);
		} catch (Exception e) {
			initiatedBy = "NA";
			e.printStackTrace();
		}
		
		return initiatedBy;
	}
	
	@RequestMapping(value = "/getUserTaskAndNotificationsCount")
	public @ResponseBody Map<String, Integer> getInitiatedByFromAppMetaData(){
		Map<String, Integer> response = new HashMap<String, Integer>();
		response.put("newTasks", adminTaskDelegate.getNewTasksCount(getUserVO()));
		response.put("newNotifications", adminTaskDelegate.getNewNotificationsCount(getUserVO()));
		return response;
	}
	
	@RequestMapping(value = "/getMedicalTypeShow")
	public @ResponseBody String getMedicalTypeShow(
			@RequestParam(value = "medicalType", required = false) String medicalType){
		
		try {
			companyInformationDelegate.setMedicalType(getUserVO(),medicalType);
			return "ok";
		} catch (LocatorException e) {
			e.printStackTrace();
		} catch (NoSuchCompanyException e) {
			e.printStackTrace();
		}
		return "error";			
	}
}
